﻿using System;
using System.Web;
using System.Web.Security;
using TraditionalMalteseCuisine.App_Code.Functions;
using TraditionalMalteseCuisine.App_Code.Objects;

namespace TraditionalMalteseCuisine
{
    public partial class SignIn : System.Web.UI.Page
    {
        #region Page Load
        protected void Page_Load(object sender, EventArgs e)
        {

        }
        #endregion


        #region Buttons
        protected void btnLogin_Click(object sender, EventArgs e)
        {
            string username = txtUsername.Text;
            string password = txtPassword.Text;
            password = Hash_Functions.HashPassword(password);

            ((MainMasterPage)Master).SiteMember = Site_Functions.DoLogin(username, password);

            if (((MainMasterPage)Master).IsLoggedIn)
            {
                if (chkRememberMe.Checked)
                {
                    SetRememberMe(((MainMasterPage)Master).SiteMember);
                }

                Response.Redirect(ContinueOn);
            }
            else
            {
                csvUsernameExists.IsValid = false;
            }
        }
        #endregion


        #region Methods
        private void SetRememberMe(SiteMember member)
        {
            // Clear any other tickets that are already in the response
            Response.Cookies.Clear();

            // Set the new expiry date - to thirty days from now
            DateTime expiryDate = DateTime.Now.AddDays(30);

            // Create a new forms authentication ticket
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(2, member.Username, DateTime.Now, expiryDate, true, string.Empty);

            // Encrypt the ticket
            string encryptedTicket = FormsAuthentication.Encrypt(ticket);

            // Create a new authentication cookie - and set its expiration date
            HttpCookie authenticationCookie = new HttpCookie("TraditionalMalteseCuisine_MemberID", encryptedTicket);
            authenticationCookie.Value = member.ID.ToString();

            authenticationCookie.Expires = ticket.Expiration;

            // Add the cookie to the response.
            Response.Cookies.Add(authenticationCookie);
        }
        #endregion


        #region Properties
        protected string ContinueOn
        {
            get { return ((Request.Params["continueon"] != null) && (Request.Params["continueon"].ToString().Length > 0) ? Request.Params["continueon"].ToString() : "default.aspx"); }
        }
        #endregion
    }
}